<?php

use Illuminate\Support\Facades\Response;

if (!function_exists('success')) {
    /**
     * 返回成功的json数组
     * @param string $msg
     * @param int $statusCode
     * @return \Illuminate\Http\JsonResponse
     */
    function success($msg = '操作成功', $statusCode = 200)
    {
        $result = [
            'statusCode' => $statusCode,
            'message' => $msg,
        ];
        return Response::json($result);
    }
}

if (!function_exists('error')) {
    /**
     * 返回失败的json数组
     * @param string $msg
     * @param int $statusCode
     * @return \Illuminate\Http\JsonResponse
     */
    function error($msg = '操作失败!', $statusCode = 302)
    {
        $result = [
            'statusCode' => $statusCode,
            'message' => $msg,
        ];
        return Response::json($result);
    }
}

if (!function_exists('data')) {
    /**
     * 返回数据集合
     *
     * @param array $data
     * @param int $statusCode
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    function data($data = [], $statusCode = 200, $message = '操作成功')
    {
        $result = [
            'statusCode' => $statusCode,
            'message' => $message,
            'data' => $data,
        ];
        return Response::json($result);
    }
}


if (!function_exists('lists_page')) {
    /**
     * 转化分页
     *
     * @param array $request
     * @param int $defaultSize
     * @param int $defaultNum
     * @return array|int[]
     */
    function lists_page($request = [], $defaultSize = 10, $defaultNum = 1)
    {
        $pageNum = $defaultNum;

        if (isset($request['pageNow'])) {
            $pageNum = $request['pageNow'];
        }
        if (isset($request['pageNum'])) {
            $pageNum = $request['pageNum'];
        }
        return array(
            'pageNow' => $pageNum,
            'pageSize' => isset($request['pageSize']) ? $request['pageSize'] : $defaultSize
        );
    }
}

if (!function_exists('lists')) {
    /**
     * @param array $data
     * @param int $statusCode
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    function lists($data = [], $statusCode = 200, $message = '操作成功')
    {
        $result = [
            'statusCode' => $statusCode,
            'message' => $message,
            'lists' => $data['data'],
            'page' => array(
                'now' => $data['current_page'],
                'size' => intval($data['per_page']),
                'count' => $data['total']
            )
        ];

        return Response::json($result);
    }
}

if (!function_exists('formatBytes')) {
    /**
     * 文件大小单位转换GB MB KB Byte
     *
     * @param $size
     * @return string
     */
    function formatBytes($size)
    {
        $units = array('Byte', 'KB', 'M', 'G', 'T');
        $i = 0;
        for (; $size >= 1024 && $i < count($units); $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $units[$i];
    }
}


if (!function_exists('format_mobile')) {
    /**
     * 格式化手机号
     *
     * @param $mobile
     * @return string
     */
    function format_mobile($mobile)
    {
        if (empty($mobile)) {
            return '';
        }
        return substr($mobile, 0, 3) . "****" . substr($mobile, -4, strlen($mobile));
    }
}

if (!function_exists('is_online')) {
    function is_online($staffer)
    {
        $id = $staffer instanceof \App\Models\Staffer\Staffer ? $staffer->id : $staffer;

        try {
            $response = resolve(\GuzzleHttp\Client::class)->get(
                sprintf(
                    '%s/apps/%s/channels/%s',
                    config('app.laravel_echo_server_url'),
                    config('app.laravel_echo_server_app_id'),
                    new \Illuminate\Broadcasting\PrivateChannel('App.Models.Staffer.Staffer.' . $id)
                ),
                [
                    'query' => ['auth_key' => config('app.laravel_echo_server_key')],
                    'timeout' => 3,
                ]
            );

            $result = json_decode($response->getBody()->getContents());

            return $result->occupied;
        } catch (Exception $exception) {
            return false;
        }
    }
}

if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端ip
     *
     * @return mixed
     */
    function get_client_ip()
    {
        if (isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP'])) { //nginx 代理模式下，获取客户端真实IP
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { //客户端的ip
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { //浏览当前页面的用户计算机的网关
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'; //浏览当前页面的用户计算机的ip地址
        } else {
            $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        }
        return $ip;
    }
}
